package com.bawei.movie.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.image.ImageOptions
import com.bawei.image.ImageStrategy
import com.bawei.image.ImgLoader
import com.bawei.movie.databinding.ItemMovieLayoutBinding
import com.bawei.common.entity.MovieEntity
import com.bumptech.glide.Glide
import kotlin.math.max

class MovieListAdapter constructor(private val list: MutableList<MovieEntity>): RecyclerView.Adapter<MovieListAdapter.MovieViewHolder>(){

    //图片框架
    private var imgLoader: ImgLoader = ImgLoader.Builder.setImageStrategy(ImageStrategy.GLIDE).build()

    private var itemClickListener: OnItemClickListener? = null

    //定义预加载函数（方法）
    var onPreload: (()->Unit)? = null
    //预加载判断最后Item个数
    var preloadItemCount = 0
    //RecyclerView滚动状态
    private var scrollState = RecyclerView.SCROLL_STATE_IDLE
    //预加载状态
    private var isPreload = false

    //普通图片参数
    private var imgOption: ImageOptions = ImageOptions.Builder
        .setImageSize(intArrayOf(80, 80))
        .setCircleImage(false)
//        .setErrorImage(com.bawei.common.R.drawable.ic_logo) //使用IO读取drawable文件下资源，存在内存消耗，尽量不用drawable下的资源
//        .setPlaceImage(com.bawei.common.R.drawable.ic_logo)
        .skipMemoryCache(true)
        .build()

    inner class MovieViewHolder(val dataBinding: ItemMovieLayoutBinding) : RecyclerView.ViewHolder(dataBinding.root)

    //设置Item点击事件
    fun setOnItemClickListener(listener: OnItemClickListener){
        itemClickListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
        return MovieViewHolder(ItemMovieLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
        val entity = list[position]
        var movieImg = holder.dataBinding.ivMovieImg
        imgLoader.loadUrlIntoImageView(holder.dataBinding.root.context, entity.videomainimag, movieImg, imgOption)
        holder.dataBinding.tvMovieTitle.text = entity.name
        holder.dataBinding.tvMovieDesc.text = entity.description
        holder.dataBinding.tvMovieTag.text = entity.taglist

        holder.dataBinding.root.setOnClickListener{
            itemClickListener?.onItemChildClick(it, position)
        }
        checkPreload(position)
    }

    /**
     * 当前View回收后，将图片组件从Glide中清除掉
     */
    override fun onViewRecycled(holder: MovieViewHolder) {
        var movieImg = holder.dataBinding.ivMovieImg
        Glide.with(holder.dataBinding.root.context).clear(movieImg)
    }

    override fun getItemCount(): Int = list.size

    override fun getItemViewType(position: Int): Int {
        return 0
    }

    override fun getItemId(position: Int): Long {
        return list[position].id.toLong()
    }

    /**
     * 当Adapter绑定到RecyclerView中的时候触发该方法
     */
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        //添加滚动事件，获取滚动状态
        recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState //记录滚动状态
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    /**
     * 检查是否满足预加载条件
     */
    private fun checkPreload(position: Int) {
        if (onPreload != null //只有设置预加载函数才触发预加载
            && position == max(list.size - 1 - preloadItemCount,0) //滚动到固定位置才触发预加载
            && scrollState != RecyclerView.SCROLL_STATE_IDLE //只有滚动状态才触发预加载
            && !isPreload //预加载过程中，不能进行过多加载
        ) {
            isPreload = true
            onPreload?.invoke()
        } else {
            //重置一下
            isPreload = false
        }
    }


    /**
     * 点击事件接口类
     */
    interface OnItemClickListener {
        fun onItemChildClick(v: View?, position: Int)
    }

}